<template>
  <el-dialog
    v-model="visible"
    title="支付确认"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="payment-dialog">
      <!-- 订单信息 -->
      <div class="order-info">
        <h3>订单信息</h3>
        <p>订单号：{{ orderData.orderNo }}</p>
        <p>支付金额：<span class="amount">¥{{ orderData.amount.toFixed(2) }}</span></p>
      </div>

      <!-- 支付方式选择 -->
      <div class="payment-methods">
        <h3>选择支付方式</h3>
        <el-radio-group v-model="selectedPaymentMethod" @change="handlePaymentMethodChange">
          <el-radio
            v-for="method in paymentMethods"
            :key="method.id"
            :label="method.id"
            class="payment-method-item"
          >
            <div class="method-content">
              <el-icon><component :is="getPaymentIcon(method.icon)" /></el-icon>
              <span>{{ method.name }}</span>
            </div>
          </el-radio>
        </el-radio-group>
      </div>

      <!-- 支付状态显示 -->
      <div v-if="paymentStatus" class="payment-status">
        <div v-if="paymentStatus === 'pending'" class="status-pending">
          <el-icon class="loading"><Loading /></el-icon>
          <span>等待支付...</span>
        </div>
        <div v-else-if="paymentStatus === 'completed'" class="status-success">
          <el-icon class="success"><SuccessFilled /></el-icon>
          <span>支付成功！</span>
        </div>
        <div v-else-if="paymentStatus === 'failed'" class="status-failed">
          <el-icon class="error"><CircleCloseFilled /></el-icon>
          <span>支付失败</span>
        </div>
      </div>

      <!-- 二维码显示 -->
      <div v-if="qrCodeUrl && paymentStatus === 'pending'" class="qr-code-section">
        <h4>请使用{{ getPaymentMethodName(selectedPaymentMethod) }}扫码支付</h4>
        <div class="qr-code">
          <img :src="qrCodeUrl" alt="支付二维码" />
        </div>
        <p class="qr-tip">请在{{ expireMinutes }}分钟内完成支付</p>
      </div>

      <!-- 现金支付确认 -->
      <div v-if="selectedPaymentMethod === 'cash' && !paymentStatus" class="cash-payment">
        <el-alert
          title="现金支付确认"
          description="请确认已收到现金后点击确认支付"
          type="warning"
          show-icon
          :closable="false"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" :disabled="processing">取消</el-button>
        <el-button
          v-if="selectedPaymentMethod === 'cash' && !paymentStatus"
          type="primary"
          @click="confirmCashPayment"
          :loading="processing"
        >
          确认收款
        </el-button>
        <el-button
          v-else-if="!paymentStatus"
          type="primary"
          @click="createPayment"
          :loading="processing"
        >
          确认支付
        </el-button>
        <el-button
          v-else-if="paymentStatus === 'completed'"
          type="success"
          @click="handleClose"
        >
          完成
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading, SuccessFilled, CircleCloseFilled, Money, CreditCard } from '@element-plus/icons-vue'
import api from '@/utils/api'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  orderData: {
    type: Object,
    required: true
  },
  paymentMethods: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'payment-success', 'payment-failed'])

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const selectedPaymentMethod = ref('cash')
const paymentStatus = ref(null) // null, 'pending', 'completed', 'failed'
const qrCodeUrl = ref('')
const processing = ref(false)
const paymentId = ref(null)
const expireTime = ref(null)
const statusCheckTimer = ref(null)

// 计算属性
const expireMinutes = computed(() => {
  if (!expireTime.value) return 15
  const now = new Date()
  const expire = new Date(expireTime.value)
  const diffMinutes = Math.ceil((expire - now) / (1000 * 60))
  return Math.max(0, diffMinutes)
})

// 方法
const getPaymentIcon = (icon) => {
  const iconMap = {
    'money': Money,
    'wechat': CreditCard,
    'alipay': CreditCard,
    'gift': CreditCard
  }
  return iconMap[icon] || Money
}

const getPaymentMethodName = (method) => {
  const methodMap = {
    'cash': '现金',
    'wechat': '微信',
    'alipay': '支付宝'
  }
  return methodMap[method] || method
}

const handlePaymentMethodChange = () => {
  // 重置支付状态
  resetPaymentStatus()
}

const resetPaymentStatus = () => {
  paymentStatus.value = null
  qrCodeUrl.value = ''
  paymentId.value = null
  expireTime.value = null
  if (statusCheckTimer.value) {
    clearInterval(statusCheckTimer.value)
    statusCheckTimer.value = null
  }
}

const createPayment = async () => {
  if (!selectedPaymentMethod.value) {
    ElMessage.warning('请选择支付方式')
    return
  }

  processing.value = true
  
  try {
    const response = await api.post('/real-payments/create', {
      orderId: props.orderData.id,
      paymentMethod: selectedPaymentMethod.value,
      amount: props.orderData.amount,
      description: `订单${props.orderData.orderNo}支付`
    })

    if (response.data.status === 'success') {
      const data = response.data.data
      
      if (selectedPaymentMethod.value === 'cash') {
        // 现金支付直接成功
        paymentStatus.value = 'completed'
        ElMessage.success('现金支付成功')
        setTimeout(() => {
          emit('payment-success', data)
          handleClose()
        }, 1500)
      } else {
        // 第三方支付
        paymentStatus.value = 'pending'
        paymentId.value = data.paymentId
        qrCodeUrl.value = data.qrCode
        expireTime.value = data.expireTime
        
        // 开始轮询支付状态
        startStatusCheck()
      }
    } else {
      ElMessage.error(response.data.message || '创建支付订单失败')
    }
  } catch (error) {
    console.error('创建支付订单失败:', error)
    ElMessage.error('创建支付订单失败')
  } finally {
    processing.value = false
  }
}

const confirmCashPayment = async () => {
  await createPayment()
}

const startStatusCheck = () => {
  if (!paymentId.value) return
  
  statusCheckTimer.value = setInterval(async () => {
    try {
      const response = await api.get(`/real-payments/${paymentId.value}/status`)
      
      if (response.data.status === 'success') {
        const status = response.data.data.paymentStatus
        
        if (status === 'completed') {
          paymentStatus.value = 'completed'
          clearInterval(statusCheckTimer.value)
          statusCheckTimer.value = null
          
          ElMessage.success('支付成功！')
          setTimeout(() => {
            emit('payment-success', response.data.data)
            handleClose()
          }, 1500)
        } else if (status === 'failed') {
          paymentStatus.value = 'failed'
          clearInterval(statusCheckTimer.value)
          statusCheckTimer.value = null
          
          ElMessage.error('支付失败')
          emit('payment-failed', response.data.data)
        }
      }
    } catch (error) {
      console.error('查询支付状态失败:', error)
    }
  }, 3000) // 每3秒查询一次
}

const handleClose = () => {
  if (paymentStatus.value === 'pending') {
    ElMessageBox.confirm('支付正在进行中，确定要关闭吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      resetPaymentStatus()
      visible.value = false
    }).catch(() => {})
  } else {
    resetPaymentStatus()
    visible.value = false
  }
}

// 监听对话框关闭
watch(visible, (newVal) => {
  if (!newVal) {
    resetPaymentStatus()
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (statusCheckTimer.value) {
    clearInterval(statusCheckTimer.value)
  }
})
</script>

<style scoped>
.payment-dialog {
  padding: 20px 0;
}

.order-info {
  margin-bottom: 30px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.order-info h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.order-info p {
  margin: 5px 0;
  color: #666;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.payment-methods h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.payment-method-item {
  display: block;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  transition: all 0.3s;
}

.payment-method-item:hover {
  border-color: #409eff;
}

.payment-method-item.is-checked {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.method-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.payment-status {
  margin: 20px 0;
  text-align: center;
}

.status-pending {
  color: #e6a23c;
}

.status-success {
  color: #67c23a;
}

.status-failed {
  color: #f56c6c;
}

.payment-status .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.loading {
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.qr-code-section {
  text-align: center;
  margin: 20px 0;
}

.qr-code-section h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.qr-code {
  display: inline-block;
  padding: 20px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.qr-code img {
  width: 200px;
  height: 200px;
}

.qr-tip {
  margin: 10px 0 0 0;
  color: #999;
  font-size: 14px;
}

.cash-payment {
  margin: 20px 0;
}

.dialog-footer {
  text-align: right;
}
</style>
